package com.itheima.controller;

import com.alibaba.druid.util.StringUtils;
import com.itheima.client.userpojo.User;
import com.itheima.client.userpojo.dto.UserDto;
import com.itheima.client.userpojo.vo.UserVo;
import com.itheima.common.JsonResult;
import com.itheima.common.RandomUtil;
import com.itheima.client.userpojo.UserSendMsgVo;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author wuzhiyong
 */
@RestController
@RequestMapping(value = "/user")
public class UserController {
    @Autowired
    private RedisTemplate<String, String> RedisTemplate;
    @Autowired
    private UserService userservice;

    /**
     * 发送短信
     * @param userSendMsgVo userSendMsgVo
     * @return JsonResult
     * @throws Exception Exception
     */
    @PostMapping(value = "/sendMsg")
    public JsonResult<Object> sendMsg(@RequestBody UserSendMsgVo userSendMsgVo) throws Exception {
        //获取手机号，验证码
        String phone = userSendMsgVo.getPhone();
        String code = RedisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return JsonResult.error(null);
        }
        //获取4位数验证码
        code = RandomUtil.getFourBitRandom();
        //给是指定手机发送短信
        // SendMsgUtil.sendMsg(phone, code);
        //将验证码存入redis 以phone为key，code为vaule并设置有效时间
        RedisTemplate.opsForValue().set(phone, code, 10, TimeUnit.MINUTES);
        return JsonResult.success("手机验证码短信发送成功", null);
    }

    /**
     * 登陆
     * @param userDto userDto
     * @return JsonResult
     */
    @PostMapping(value = "/login")
    public JsonResult<UserVo> login(@RequestBody UserDto userDto) {
        UserVo login = userservice.login(userDto);
        if (login != null) {
            return JsonResult.success(login, null);
        }
        return JsonResult.error("验证码错误");
    }

    /**
     * 登出
     * @param request request
     * @return JsonResult
     */
    @PostMapping(value = "/loginout")
    public JsonResult<String> loginout(HttpServletRequest request) {
        userservice.logout(request);
        return JsonResult.success("登出成功", null);
    }
}
